//
//  BHLocationManager.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/8/5.
//

import UIKit
import AMapLocationKit

class BHLocationManager: NSObject {
    
    static let shared: BHLocationManager = BHLocationManager.init()
    
    lazy var locationManager: AMapLocationManager = {
        let manager = AMapLocationManager.init()
        manager.desiredAccuracy = kCLLocationAccuracyHundredMeters
        manager.locationTimeout = 2
        manager.reGeocodeTimeout = 2
        return manager
    }()
    
    lazy var systemManager: CLLocationManager = {
        let manager = CLLocationManager.init()
        return manager
    }()
    
    var longitude: String = ""
    var latitude: String = ""
    
    var latitude_float: CGFloat = 0.00
    var longitude_float: CGFloat = 0.00

    
    var location: CLLocation?
    
    var authed: Bool = false
    var cityName: String = "南京"
    
    
    func requestLocation()  {
        self.systemManager.requestWhenInUseAuthorization()
        self.systemManager.requestAlwaysAuthorization()
        self.systemManager.delegate = self
    }
    
}

extension BHLocationManager {
    func amapLocation()  {
        self.locationManager.requestLocation(withReGeocode: true, completionBlock: { (location: CLLocation?, reGeocode: AMapLocationReGeocode?, error: Error?) in
                    
            if let error = error {
                let error = error as NSError
                
                if error.code == AMapLocationErrorCode.locateFailed.rawValue {
                    //定位错误：此时location和regeocode没有返回值，不进行annotation的添加
                    NSLog("定位错误:{\(error.code) - \(error.localizedDescription)};")
                    return
                }
                else if error.code == AMapLocationErrorCode.reGeocodeFailed.rawValue
                    || error.code == AMapLocationErrorCode.timeOut.rawValue
                    || error.code == AMapLocationErrorCode.cannotFindHost.rawValue
                    || error.code == AMapLocationErrorCode.badURL.rawValue
                    || error.code == AMapLocationErrorCode.notConnectedToInternet.rawValue
                    || error.code == AMapLocationErrorCode.cannotConnectToHost.rawValue {
                    
                    //逆地理错误：在带逆地理的单次定位中，逆地理过程可能发生错误，此时location有返回值，regeocode无返回值，进行annotation的添加
                    NSLog("逆地理错误:{\(error.code) - \(error.localizedDescription)};")
                }
                else {
                    //没有错误：location有返回值，regeocode是否有返回值取决于是否进行逆地理操作，进行annotation的添加
                    self.longitude = "\(location!.coordinate.longitude)"
                    self.latitude = "\(location!.coordinate.latitude)"
                }
            }
            
            if let location = location {
                NSLog("location:%@", location)
                self.location = location
                self.longitude = "\(location.coordinate.longitude)"
                self.latitude = "\(location.coordinate.latitude)"
                
                self.latitude_float = CGFloat(location.coordinate.latitude)
                self.longitude_float = CGFloat(location.coordinate.longitude)
                self.authed = true
            }
            
            if let reGeocode = reGeocode {
                NSLog("reGeocode:%@", reGeocode)
                if BHPlatform.isSimulator == false {
                    self.cityName = reGeocode.city
                }else {
                    self.cityName = "南京"
                }
                
                NotificationCenter.default.post(name: NSNotification.Name.init(String.refreshCityKey), object: nil)
            }
        })
    }
}

extension BHLocationManager: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        
        case .denied:
            BHCommonTool.showAlertWith(showVC: nil, title: nil, message: "请在设置->隐私->定位中打开定位权限", okBtn: "知道了", cancel: nil) { (confirm) in
                
            }
            break
        case .restricted: // 定位受限制
            BHCommonTool.showAlertWith(showVC: nil, title: nil, message: "请在设置->隐私->定位中打开定位权限", okBtn: "知道了", cancel: nil) { (confirm) in
                
            }
            break
            
        case .authorizedAlways:
            self.amapLocation()
            break
        case .authorizedWhenInUse:
            self.amapLocation()
            break
   
        default:
            break
        }
    }
}
